package editer.views 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.InteractiveObject;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.display.StageDisplayState;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;
	import org.osflash.signals.natives.sets.InteractiveObjectSignalSet;
	import org.osflash.signals.natives.sets.LoaderInfoSignalSet;
	import org.osflash.signals.natives.sets.StageSignalSet;
	import org.osflash.signals.natives.sets.TextFieldSignalSet;
	import org.robotlegs.xxl.mvcs.Mediator;
	import org.xxl.iso.DrawnIsoTile;
	import org.xxl.iso.IsoUtil;
	import org.xxl.iso.IsoWorld;
	import org.xxl.iso.MapConfig;
	import org.xxl.iso.Point3D;
	import org.xxl.structure.Direction;
	import org.xxl.utils.GameTimer;
	import org.xxl.views.core.IToggle;
	
	/**
	 * ...
	 * @author XXL
	 */
	public class UIMediator extends Mediator 
	{
		private var loader:Loader;
		
		[Inject]
		public var view:UI;
		
		[Inject(name = "isoLayer")]
		public var isoLayer:Sprite;
		
		[Inject]
		public var stats:Stats;
		
		[Inject(name = "bgLayer")]
		public var bgLayer:Sprite;
		
		private var isoWorld:IsoWorld;
		private var isoWorldSignalSet:InteractiveObjectSignalSet;
		
		override public function onRegister():void 
		{
			super.onRegister();
			
			loader = new Loader();
			(new LoaderInfoSignalSet(loader.contentLoaderInfo)).complete.addOnce(complete);
			loader.load(new URLRequest("../assets/ui.swf"));
		}
		
		private var tmpW:int = 10;
		private var tmpH:int = 10;
		private var tmpS:int = 50;
		private function complete(e:Event):void 
		{
			var cls:Class = loader.contentLoaderInfo.applicationDomain.getDefinition("UI") as Class;
			this.view.buildTemplete(new cls);
			
			isoWorld = new IsoWorld(tmpW, tmpH, tmpS);
			isoWorld.showGrid = true;
			isoWorld.render();
			isoLayer.addChild(isoWorld);
			
			this.view.wTxt.text = tmpW.toString();
			this.view.hTxt.text = tmpH.toString();
			this.view.sizeTxt.text = tmpS.toString();
			this.view.xPosTxt.text = "0";
			this.view.yPosTxt.text = "0";
			isoWorld.reInit(tmpW, tmpH, tmpS);
			isoWorld.render();
			(new InteractiveObjectSignalSet(this.view.loadPicBtn)).click.addOnce(loadPic);
			
			(new TextFieldSignalSet(this.view.wTxt)).change.add(txtChangeFun);
			(new TextFieldSignalSet(this.view.hTxt)).change.add(txtChangeFun);
			(new TextFieldSignalSet(this.view.sizeTxt)).change.add(txtChangeFun);
			
			(new InteractiveObjectSignalSet(this.view.resizeBtn)).click.add(resize);
			GameTimer.GetInstance().frameSignal.add(frameHandler);
			
			(new InteractiveObjectSignalSet(this.view.startDragBtn)).click.add(dragFun);
			(new InteractiveObjectSignalSet(this.view.stopDragBtn)).click.add(dragFun);
			
			(new InteractiveObjectSignalSet(this.view.zoomBtn)).click.add(zoomFun);
			(new StageSignalSet(contextView.stage)).resize.add(resizeHandler);
			
			(new InteractiveObjectSignalSet(this.view.aAndHBtn)).click.add(activeAndHide);
			
			var ioss:InteractiveObjectSignalSet;
			ioss = (new InteractiveObjectSignalSet(this.view.downBtn));
			ioss.mouseDown.add(mapMove);
			ioss.mouseUp.add(stopMapMove);
			ioss = (new InteractiveObjectSignalSet(this.view.upBtn));
			ioss.mouseDown.add(mapMove);
			ioss.mouseUp.add(stopMapMove);
			ioss = (new InteractiveObjectSignalSet(this.view.leftBtn));
			ioss.mouseDown.add(mapMove);
			ioss.mouseUp.add(stopMapMove);
			ioss = (new InteractiveObjectSignalSet(this.view.rightBtn));
			ioss.mouseDown.add(mapMove);
			ioss.mouseUp.add(stopMapMove);
			
			(new InteractiveObjectSignalSet(this.view.moveableBtn1.skin as InteractiveObject)).click.add(setMoveable);
			(new InteractiveObjectSignalSet(this.view.moveableBtn2.skin as InteractiveObject)).click.add(setMoveable);
			(new InteractiveObjectSignalSet(this.view.maskBtn1.skin as InteractiveObject)).click.add(setMaskable);
			(new InteractiveObjectSignalSet(this.view.maskBtn2.skin as InteractiveObject)).click.add(setMaskable);
			
			toggleList1.push(this.view.moveableBtn1);
			toggleList1.push(this.view.moveableBtn2);
			toggleList1.push(this.view.maskBtn1);
			toggleList1.push(this.view.maskBtn2);
			
			(new InteractiveObjectSignalSet(this.view.outputBtn)).click.add(output);
		}
		
		private function output(e:MouseEvent):void 
		{
			var mapConfig:MapConfig = new MapConfig();
			mapConfig.id = "test";
			mapConfig.bgIDs = ["1"];
			mapConfig.bgXYs = [[0, 0]];
			mapConfig.tX = (isoWorld.x - bgLayer.x);
			mapConfig.tY = (isoWorld.y - bgLayer.y);
			mapConfig.w = tmpW;
			mapConfig.h = tmpH;
			mapConfig.size = tmpS;
			var logics:Object = { };
			var index:String;
			for (index in logic_moveables)
			{
				if (logics[index] == undefined)
				{
					logics[index] = 0;
				}
				logics[index] = logics[index] | LOGIC_MOVEABLE;
			}
			for (index in logic_maskables)
			{
				if (logics[index] == undefined)
				{
					logics[index] = 0;
				}
				logics[index] = logics[index] | LOGIC_MASK;
			}
			mapConfig.logics = [];
			for (index in logics)
			{
				var logicStr:String = index + "_" + logics[index];
				mapConfig.logics.push(logicStr);
			}
			var bytes:ByteArray = new ByteArray();
			bytes.writeObject(mapConfig);
			bytes.compress();
			var file:FileReference = new FileReference();
			file.save(bytes, ".dat");
		}
		
		private var toggleList1:Vector.<IToggle> = new Vector.<IToggle>();
		private function setMoveable(e:MouseEvent):void
		{
			for each(var toggle:IToggle in toggleList1)
			{
				toggle.selected = false;
			}
			if (e.currentTarget == this.view.moveableBtn1.skin)
			{
				this.view.moveableBtn1.selected = true;
			}
			else
			{
				this.view.moveableBtn2.selected = true;
			}
			
			if (isoWorldSignalSet == null)
			{
				isoWorldSignalSet = new InteractiveObjectSignalSet(isoWorld);
			}
			isoWorldSignalSet.click.add(logicFun);
		}
		
		private function setMaskable(e:MouseEvent):void
		{
			for each(var toggle:IToggle in toggleList1)
			{
				toggle.selected = false;
			}
			if (e.currentTarget == this.view.maskBtn1.skin)
			{
				this.view.maskBtn1.selected = true;
			}
			else
			{
				this.view.maskBtn2.selected = true;
			}
			if (isoWorldSignalSet == null)
			{
				isoWorldSignalSet = new InteractiveObjectSignalSet(isoWorld);
			}
			isoWorldSignalSet.click.add(logicFun);
		}
		
		private static const LOGIC_MOVEABLE:int = 1;
		private static const LOGIC_MASK:int = 2;
		private var logic_moveables:Object = { };
		private var logic_maskables:Object = { };
		private function logicFun(e:Event):void
		{
			var tile:DrawnIsoTile;
			var pos:Point3D = IsoUtil.ScreenToIso(new Point(isoWorld.mouseX, isoWorld.mouseY));
			pos.x = Math.round(pos.x / tmpS) * tmpS;
			pos.y = Math.round(pos.y / tmpS) * tmpS;
			pos.z = Math.round(pos.z / tmpS) * tmpS;
			var ix:int = pos.x / tmpS;
			var iy:int = pos.z / tmpS;
			var index:String = ix + "_" + iy;
			if (this.view.moveableBtn1.selected)
			{
				if (logic_moveables[index])
				{
					tile = logic_moveables[index];
					isoWorld.removeChildFromWorld(tile);
					delete logic_moveables[index];
				}
				else
				{
					tile = new DrawnIsoTile(this.tmpS, 0x00FF00);
					tile.position = pos;
					isoWorld.addChildToWorld(tile);
					logic_moveables[index] = tile;
				}
			}
			else if (this.view.maskBtn1.selected)
			{
				if (logic_maskables[index])
				{
					tile = logic_maskables[index];
					isoWorld.removeChildFromWorld(tile);
					delete logic_maskables[index];
				}
				else
				{
					tile = new DrawnIsoTile(this.tmpS, 0xFF0000);
					tile.position = pos;
					isoWorld.addChildToWorld(tile);
					logic_maskables[index] = tile;
				}
			}
			isoWorld.render();
		}
		
		private var startInteractiveSignalSet:InteractiveObjectSignalSet;
		private function mapMove(e:MouseEvent):void
		{
			if (startInteractiveSignalSet == null)
			{
				startInteractiveSignalSet = new InteractiveObjectSignalSet(contextView.stage);
			}
			startInteractiveSignalSet.mouseUp.add(stopMapMove);
			if (e.currentTarget == this.view.downBtn)
			{
				mapMoveFlag = Direction.DOWN;
			}
			else if (e.currentTarget == this.view.upBtn)
			{
				mapMoveFlag = Direction.UP;
			}
			else if (e.currentTarget == this.view.leftBtn)
			{
				mapMoveFlag = Direction.LEFT;
			}
			else if (e.currentTarget == this.view.rightBtn)
			{
				mapMoveFlag = Direction.RIGHT;
			}
			GameTimer.GetInstance().frameSignal.add(mapMoveRun);
		}
		
		private function stopMapMove(e:Event):void 
		{
			GameTimer.GetInstance().frameSignal.remove(mapMoveRun);
		}
		
		private var mapMoveFlag:int;
		private function mapMoveRun(interval:int):void 
		{
			var tmp:int;
			if (mapMoveFlag == Direction.DOWN)
			{
				this.bgLayer.y -= 10;
				this.isoWorld.y -= 10;
			}
			else if (mapMoveFlag == Direction.UP)
			{
				this.bgLayer.y += 10;
				this.isoWorld.y += 10;
			}
			else if (mapMoveFlag == Direction.LEFT)
			{
				this.bgLayer.x += 10;
				this.isoWorld.x += 10;
			}
			else if (mapMoveFlag == Direction.RIGHT)
			{
				this.bgLayer.x -= 10;
				this.isoWorld.x -= 10;
			}
		}
		
		private var activeFlag:Boolean = true;
		private function activeAndHide(e:Event):void 
		{
			if (activeFlag)
			{
				this.view.skin.x = -this.view.skin.width + 20;
				this.view.skin.y = contextView.stage.stageHeight - 20;
				this.stats.visible = false;
			}
			else
			{
				this.view.skin.x = 0;
				this.view.skin.y = 0;
				this.stats.visible = true;
			}
			activeFlag = !activeFlag;
		}
		
		private function resizeHandler(e:Event):void 
		{
			if (!activeFlag)
			{
				this.view.skin.y = contextView.stage.stageHeight - 20;
			}
		}
		
		private function zoomFun(e:Event):void 
		{
			if (contextView.stage.displayState.toLowerCase() == StageDisplayState.FULL_SCREEN.toLowerCase())
			{
				contextView.stage.displayState = StageDisplayState.NORMAL;
			}
			else
			{
				contextView.stage.displayState = StageDisplayState.FULL_SCREEN;
			}
		}
		
		private function dragFun(e:MouseEvent):void 
		{
			if (e.currentTarget == this.view.startDragBtn)
			{
				if (isoWorldSignalSet == null)
				{
					isoWorldSignalSet = new InteractiveObjectSignalSet(isoWorld);
				}
				isoWorldSignalSet.mouseDown.add(isoWorldMouseHandler);
				isoWorldSignalSet.mouseUp.add(isoWorldMouseHandler);
				(new InteractiveObjectSignalSet(contextView.stage)).mouseUp.addOnce(isoWorldMouseHandler);
			}
			else
			{
				if (isoWorldSignalSet)
				{
					isoWorldSignalSet.removeAll();
				}
			}
		}
		
		private var dragFlag:Boolean = false;
		private function isoWorldMouseHandler(e:MouseEvent):void 
		{
			for each(var toggle:IToggle in toggleList1)
			{
				toggle.selected = false;
			}
			if (e.type == MouseEvent.MOUSE_DOWN)
			{
				isoWorld.startDrag();
				dragFlag = true;
			}
			else
			{
				isoWorld.stopDrag();
				dragFlag = false;
			}
		}
		
		private function frameHandler(interval:int):void 
		{
			this.view.xPosTxt.text = (isoWorld.x - bgLayer.x).toString();
			this.view.yPosTxt.text = (isoWorld.y - bgLayer.y).toString();
		}
		
		private function resize(e:Event):void 
		{
			tmpW = int(this.view.wTxt.text);
			tmpH = int(this.view.hTxt.text);
			tmpS = int(this.view.sizeTxt.text);
			isoWorld.reInit(tmpW, tmpH, tmpS);
			isoWorld.render();
			this.view.wTxt.backgroundColor = 0xFFFFFF;
			this.view.hTxt.backgroundColor = 0xFFFFFF;
			this.view.sizeTxt.backgroundColor = 0xFFFFFF;
		}
		
		private function txtChangeFun(e:Event):void 
		{
			if (this.view.wTxt.text != tmpW.toString())
			{
				this.view.wTxt.backgroundColor = 0xFF0000;
			}
			else
			{
				this.view.wTxt.backgroundColor = 0xFFFFFF;
			}
			if (this.view.hTxt.text != tmpH.toString())
			{
				this.view.hTxt.backgroundColor = 0xFF0000;
			}
			else
			{
				this.view.hTxt.backgroundColor = 0xFFFFFF;
			}
			if (this.view.sizeTxt.text != tmpS.toString())
			{
				this.view.sizeTxt.backgroundColor = 0xFF0000;
			}
			else
			{
				this.view.sizeTxt.backgroundColor = 0xFFFFFF;
			}
			
		}
		
		private function loadPic(e:Event):void 
		{
			loader = new Loader();
			(new LoaderInfoSignalSet(loader.contentLoaderInfo)).complete.addOnce(picComplete);
			loader.load(new URLRequest("../assets/back2.swf"));
		}
		
		private function picComplete(e:Event):void 
		{
			var cls:Class = loader.contentLoaderInfo.applicationDomain.getDefinition("Image") as Class;
			var bitmapData:BitmapData = new cls(1368, 783);
			this.bgLayer.addChild(new Bitmap(bitmapData));
		}
		
	}

}